package com.neulogistics.contrib.warehouse.api.application.command.handler;

import com.blackto.lib.mediat.unicast.IRequestHandler;
import com.neulogistics.contrib.warehouse.api.application.command.CreateWarehouseCommand;
import com.neulogistics.contrib.warehouse.api.application.rpc.IGeographyService;
import com.neulogistics.contrib.warehouse.domain.model.aggregate.Warehouse;
import com.neulogistics.contrib.warehouse.domain.model.enumeration.WarehouseLevel;
import com.neulogistics.contrib.warehouse.domain.model.valueobject.Address;
import com.neulogistics.contrib.warehouse.domain.repository.IWarehouseRepository;
import com.neulogistics.infrastructure.common.serviceresult.BaseResponse;
import com.neulogistics.infrastructure.common.serviceresult.ResultUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class CreateWarehouseCommandHandler implements IRequestHandler<CreateWarehouseCommand, BaseResponse<String>> {
    @Resource
    private IWarehouseRepository warehouseRepository;

    @Resource
    private IGeographyService geographyService;


    @Override
    public BaseResponse<String> handle(CreateWarehouseCommand command) {
        // command转化为实体
        String warehouseName = command.getWarehouseName();
        Address warehouseAddress = command.getWarehouseAddress();
        // 获取库房经纬度
        warehouseAddress.setLocation(geographyService.getLocation(warehouseAddress));
        WarehouseLevel warehouseLevel = WarehouseLevel.fromValue(command.getWarehouseLevel(), WarehouseLevel.class);

        // 创建实体
        Warehouse warehouse = new Warehouse(warehouseName, warehouseAddress, warehouseLevel);

        // 持久化存储
        warehouseRepository.save(warehouse);

        return ResultUtils.success(warehouse.getWarehouseId().toString());
    }
}
